<template>
  <div>
    <el-dialog :visible.sync="dialog" :append-to-body="true" :before-close="cancel" title="上传图片" width="500px">
      <el-upload
        :action="fileUploadApi + '?name=' + picName"
        list-type="picture-card"
        :on-success="handleSuccess"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="onBeforeUpload"
        :headers="headers"
        :limit="3"
        :on-exceed="handleExceed"
        :file-list="fileList"
        accept="image/jpeg,image/jpg,image/png"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button type="primary" @click="onOk">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      headers: { 'Authorization': getToken() },
      dialogImageUrl: '',
      dialogVisible: false,
      picName: '',
      fileList: [],
      filePath: '',
      dialog: false,
      row: null
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    cancel() {
      this.fileList = []
      this.dialog = false
    },
    onOk() {
      this.row.filePath = this.filePath
      this.$emit('tell', this.row)
      this.fileList = []
      this.dialog = false
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.picName = file.name
      return isIMAGE && isLt1M
    },
    handleSuccess(response, file, fileList) {
      this.filePath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    handleRemove(file, fileList) {
      this.filePath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
